<?php
namespace backend\controllers;

use Yii;
use yii\data\Pagination; //分页
use backend\base\BaseController;
use backend\models\AdminModel;

/**
 * Site controller
 */
class SiteController extends BaseController
{
    /**
     * 欢迎页
     * @return string
     */
    public function actionIndex()
    {
        return $this->redirect(array('site/login'));
    }

    /**
     * 登录
     * @return array|string
     */
    public function actionLogin()
    {
        Yii::$app->layout = false;
        $data = parent::parseData($this->body);
        if (!empty($data)) {
            $platformUser = AdminModel::find()->andWhere(['status'=>1])->andWhere(['or',['username'=>$data['mobile']],['mobile'=>$data['mobile']]])->one();
            if($platformUser){
                $data['mobile'] = $platformUser->mobile;
                $model = new AdminModel(['scenario' => 'login']);
                if ($model->load($data, '') && $model->validate()) {//电话登录
                    if ($admin = $model->loginValidate()) {  //查找到并且密码匹配，登录
                        // Yii::$app->user->login($admin, 3600 * 2);
                        Yii::$app->cache->set('admin', $admin->attributes, 60*60);
                        return json_encode(parent::ajaxReturn('operate_success_login', []));
                    }
                }
            }
            return json_encode(parent::ajaxReturn('login_error', []));//查不到账号或者密码错误
        }
        return $this->render('login');
    }

    /**
     * 登出
     * @return array
     */
    public function actionLogout()
    {
        return $this->redirect(array('site/login'));
    }

    /*
     * 默认进入首页
     */
    public function actionDemo()
    {
        Yii::$app->layout = 'main';
        return $this->render('demo', array(

        ));
    }

    /*
     * 用户列表
     */
    public function actionList()
    {
        $data = parent::parseData($this->body);
        $admin = new AdminModel();
        $model = $admin->getList($data);
        if(!empty($model['data'])){
            foreach ($model['data'] as $k => $v) {
                //创建人
                $model['data'][$k]['creator'] = AdminModel::find()->select(['username'])->where(['id' => $v['creator_id']])->one()['username'];
                $model['data'][$k]['role'] = Yii::$app->params['role'][$v['role']]['level'];
            }
        }
        $pagination=new Pagination([
            'pageSize' =>15,
            'totalCount'      =>$model['count'],
        ]);
        return $this->render('list',array(
            'model' => $model['data'],
            'pagination'=>$pagination,
            'data'=>$data
        ));
    }

    /*
     * 新增用户
     */
    public function actionAddAjaxDo()
    {
        $data = parent::parseData($this->body);
        $admin = new AdminModel(['scenario' => 'add']);
        $data['creator_id'] = Yii::$app->cache->get('admin')['id'];
        if(!empty($data)){
            if ($admin->load($data, '') && $admin->validate()) {
                if($admin->save()){
                    return json_encode(parent::ajaxReturn('operate_success_add', []));
                }
            }
            $errorMsg = array_values($admin->getErrors());//报错信息
            return json_encode(parent::ajaxCustom('80000', $errorMsg));
        }
        return json_encode(parent::ajaxCustom('80000', '参数错误', []));//返回参数验证失败信息
    }

    /*
     * 修改密码
     */
    public function actionEditPasswordAjaxDo()
    {
        $data = parent::parseData($this->body);
        if(!empty($data)){
            $data['id'] = Yii::$app->cache->get('admin')['id'];
            if($data['new_password'] != $data['repet_password']){
                return json_encode(parent::ajaxReturn('new_pass_error', []));
            }
            if($data['new_password'] == $data['old_password']){
                return json_encode(parent::ajaxReturn('new_old_pass_error', []));
            }
            $user = AdminModel::find()->select(['password'])->where(['id'=>Yii::$app->cache->get('admin')['id']])->asArray()->one();
            if(!password_verify($data['old_password'], $user['password'])){
                return json_encode(parent::ajaxReturn('old_pass_error', []));//原密码错误
            }
            $admin = new AdminModel(['scenario' => 'edit_pass']);
            if ($admin->load($data, '') && $admin->validate()) {
                $password = password_hash($data['new_password'], PASSWORD_DEFAULT, []);
                $count = $admin->updateAll(['password'=>$password],'id=:id',array(':id'=>$data['id']));
                if($count> 0){
                    return json_encode(parent::ajaxReturn('operate_success_edit', []));
                }
            }
            $errorMsg = array_values($admin->getErrors());//报错信息
            return json_encode(parent::ajaxCustom('80000', $errorMsg));
        }
        return json_encode(parent::ajaxCustom('80000', '参数错误', []));//返回参数验证失败信息
    }

    /*
     * 删除账户
     */
    public function actionDeleAjaxDo()
    {
        $data = parent::parseData($this->body);
        if(!empty($data)){
            $admin = new AdminModel(['scenario' => 'delete']);
            if ($admin->load($data, '') && $admin->validate()) {
                if(!empty($data['type'])){
                    if($data['type'] == 1){
                        $count = $admin->updateAll(['status'=>2],'id=:id',array(':id'=>$data['id']));
                    }elseif($data['type'] == 2){
                        $count = $admin->updateAll(['status'=>1],'id=:id',array(':id'=>$data['id']));
                    }
                }else{
                    $count = $admin->updateAll(['status'=>0],'id=:id',array(':id'=>$data['id']));
                }
                if($count> 0){
                    return json_encode(parent::ajaxReturn('operate_success_edit', []));
                }
            }
            $errorMsg = array_values($admin->getErrors());//报错信息
            return json_encode(parent::ajaxCustom('80000', $errorMsg));
        }
        return json_encode(parent::ajaxCustom('80000', '参数错误', []));//返回参数验证失败信息
    }

}
